<template>
  <!-- 表格模块-->
  <div class="tableRow">
    <el-row class="select-list" v-permission="'bus:seal:query'">
       <el-form :inline="true" ref="selectForm" label-position="right" label-width="80px"
               :model="selectFormModel" size="mini">
        <el-form-item label="名称" prop="name">
          <el-input v-model="selectFormModel.name" placeholder="名称" clearable
          @keyup.enter.native="onSearch"/>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-tree-select v-model="selectFormModel.deptId" :selectParams="dialog.selectParams"
                            :treeParams="dialog.treeParams"
                            @searchFun="searchTreeFun" ref="searchTreeSelect" @keyup.enter.native="onSearch"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select value="0" v-model="selectFormModel.status" placeholder="状态" style="width: 200px" @keyup.enter.native="onSearch">
            <el-option label="正常" value="0"/>
            <el-option label="停用" value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" plain round @click="onSearch">搜索
          </el-button>
          <el-button type="warning" icon="el-icon-refresh" size="mini" plain round
                     @click="onRefreshSelectForm()">重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 表格操作按钮 增删改查-->
    <el-row class="toolbar">
      <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="handleAdd"
                 v-permission="'bus:seal:add'">
        新增
      </el-button>
      <el-button type="info" icon="el-icon-edit" :disabled="dialog.isBatchEditDisabled" size="mini" plain
                 @click="handleEdit" v-permission="'bus:seal:edit'"> 编辑
      </el-button>
      <el-button type="danger" icon="el-icon-delete" :disabled="dialog.isBatchRemoveDisabled" size="mini" plain
                 @click="handleBatchDelete" v-permission="'bus:seal:remove'"> 删除
      </el-button>
    </el-row>

    <!-- 表格模块 -->
    <data-table ref="dataTable"
                :api="getSealList"
                :options="options"
                :columns="columns"
                :operates="operates"
                :query="selectFormModel"
                @handle-selection-change="handleSelectionChange"/>


    <!-- 弹窗 -->
    <el-dialog :title="dialog.title"
               :visible.sync="dialog.dialogFormVisible"
               :modal-append-to-body="false"
               :destroy-on-close="false"
               @close="closeDialog"
               width="600px">
      <el-form :model="addModel" ref="addForm" label-width="100px" :rules="addFormRules" size="small">

        <el-form-item label="名称" prop="subTitle">
          <el-input v-model="addModel.name" placeholder="名称"/>
        </el-form-item>
        <el-form-item label="用途" prop="purpose">
          <el-input v-model="addModel.purpose" placeholder="用途"/>
        </el-form-item>
        <el-form-item label="图片" prop="imange">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="headers">
            <img v-if="dialog.imageUrl" :src="dialog.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过6Mb</div>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-tree-select v-model="addModel.deptId" :selectParams="dialog.selectParams"
                            :treeParams="dialog.treeParams"
                            @searchFun="searchFun" ref="treeSelect" lazy/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="addModel.status" active-color="#13ce66" inactive-color="#ff4949"
                     active-text="正常"
                     inactive-text="停用"
                     active-value="0"
                     inactive-value="1">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.dialogFormVisible=false" size="medium">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="medium">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialog.imageVisible">
      <img width="100%" :src="dialog.imageUrl" alt="">
    </el-dialog>
  </div>
</template>

<!-- 脚本模块  -->
<script lang="ts">
import {Component, Ref, Vue} from 'vue-property-decorator';
import DataTable from '@/components/DataTable/DataTable.vue';
import store from '@/store';

import {
  addSeal,
  getSealList,
  removeSeal,
  updateSeal,
  checkSealNameUnique,
} from '@/api/seal';

import {
  userTreeSelectDept
} from '@/api/dept';

import {validateForm} from '@/utils';


@Component({components: {DataTable}})
export default class Area extends Vue {
  data: Array<any> = [];
  @Ref('addForm') private addForm!: any;
  @Ref('treeSelect')  treeSelect!: any;
  @Ref('searchTreeSelect')  searchTreeSelect!: any;
  @Ref('selectForm') private selectForm!: any;
  @Ref('dataTable') private dataTable!: any;
  private getSealList: any = getSealList;
  uploadAction = process.env.VUE_APP_BASE_API  +'/resources/upload'

  headers: any = {
    'Authorization': 'Bearer ' + store.getters.token
  };

  columns: any = [
  {
      label: 'ID',
      prop: 'id',
      hide: true
    },
    {
      label: '名称',
      prop: 'name'
    },
    {
      label: '用途',
      prop: 'purpose',
    },
    {
      label: '部门名称',
      prop: 'deptName'
    },
    {
      label: '状态', prop: 'status', sortable: 'custom', render: function (createElement, row) {
        if (row && row.row && row.row.status === '0') {
          return createElement('el-tag', {
              attrs: {
                type: 'success'
              }
            }, ['正常']
          );
        } else if (row && row.row && row.row.status === '1') {
          return createElement('el-tag', {
              attrs: {
                type: 'warning'
              }
            }, ['停用']
          );
        } else {
          return createElement('el-tag', {
              attrs: {
                type: 'danger'
              }
            }, ['未知']
          );
        }
      },
      width: 60
    },
    {label: '创建时间', prop: 'createTime', sortable: 'custom', width: 160, showOverflowTooltip: true}
  ];
  operates: any = {
    width: 200,
    fixed: 'right',
    list: [
      {
        label: '编辑',
        type: 'warning',
        icon: 'el-icon-edit',
        plain: true,
        disabled: () => {
          return false;
        },
        permission: 'bus:seal:edit',
        method: (index, row) => {
          this.handleEdit(index, row);
        }
      },
      {
        label: '删除',
        type: 'danger',
        icon: 'el-icon-delete',
        plain: true,
        disabled: () => {
          return false;
        },
        permission: 'bus:seal:remove',
        method: (index, row) => {
          this.handleDelete(index, row);
        }
      }
    ]
  };
  addModel: any = {
    deptId: 0,
    name: '',
    purpose: '',
    status: '0',
    image: ''
  };

  options: any = {
    stripe: true, // 是否为斑马纹 table
    loading: false, // 是否添加表格loading加载动画
    highlightCurrentRow: true, // 是否支持当前行高亮显示
    multipleSelect: true, // 是否支持列表项选中功能
  };


  
  selectFormModel: any = {
    name: '',
    deptId: '',
    status:'0'
  };

  addFormRules: any = {
    name: [
      {validator: this.validatNameUnique, trigger: 'change'},
    ]
  };
  dialog: any = {
    imageUrl: '',
    imageVisible: false,
    imgaeDisabled: false,
    categoryData:[],
    dialogFormVisible: false,
    title: '对话框',
    isEdit: false,
    isBatchEditDisabled: true,
    isBatchRemoveDisabled: true,
    formData: [],
    selectParams: {
      clearable: true,
      placeholder: '请选择部门'
    },
    treeParams: {
      clickParent: true,
      filterable: true,
      accordion: true,
      defaultExpandAll:true,
      highlightCurrent:true,
      data: [],
      props: {
        children: 'children',
        label: 'label',
        disabled: 'disabled',
        value: 'id'
      }
    }
  };
 

  /*验证区域名称是否唯一*/
  validatNameUnique(rule: any, value: any, callback: any) {
    checkSealNameUnique({
      name: value,
      deptId: this.addModel.deptId
    }).then((res: any) => {
      if (res.data && res.data === '0') {
        callback();
      } else {
        callback(new Error('印章名称已经存在'));
      }
    }).catch((err: any) => {
      console.error(err);
      callback(new Error('印章名称已经存在'));
    })
  }

  handleAvatarSuccess(res, file) {
    this.addModel.image = res.data.id;
    this.dialog.imageUrl = process.env.VUE_APP_BASE_API +res.data.resource;
  }

  /*新增*/
  handleAdd() {
    this.dialog.title = '新增';
    this.dialog.isEdit = false;
    this.dialog.dialogFormVisible = true;
    this.dialog.imageUrl ='';
  }

  /*编辑*/
  handleEdit(index: number, row: any) {
    this.dialog.title = '编辑';
    this.dialog.isEdit = true;
    this.addModel = Object.assign({}, row || this.dialog.formData[0]);
   // const id = (row && row.id) ? row.id : this.dialog.formData[0].id;

    this.dialog.imageUrl = (this.addModel && this.addModel.image)? (process.env.VUE_APP_BASE_API + '/resources/file/' + this.addModel.image ) : '';
    this.dialog.dialogFormVisible = true;
  }

  /*批量删除*/
  handleBatchDelete() {
    //删除
    this.$confirm('确定要删除选定数据吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const ids: Array<any> = [];
      this.dialog.formData.forEach((item, index) => {
        ids[index] = item.id;
      });
      return removeSeal({'ids': ids});
    }).then((response: any) => {
      this.dataTable.refresh();
      this.$message.success(response.msg);
    }).catch((e) => {
      console.error(e);
    });
  }

  /*删除*/
  handleDelete(index: number, row: any) {
    this.$confirm('确定要删除该数据吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      return removeSeal({'ids': [row.id]});
    }).then((response: any) => {
      this.dataTable.refresh();
      this.$message.success(response.msg);
    }).catch((e) => {
      console.error(e);
    });
  }

  submitForm(): void {
    this.addForm.validate((valid: boolean) => {
      if (valid) {
        
        if (this.dialog.isEdit) {
          //编辑
          updateSeal(this.addModel).then((response: any) => {
            this.dataTable.refresh();
            this.dialog.dialogFormVisible = false;
            this.$message.success(response.msg);
          }).catch((e) => {
            console.error(e);
            validateForm(e.data, this.addForm, this.addFormRules);
          });
        } else {
          //新增
          addSeal(this.addModel).then((response: any) => {
            this.dataTable.refresh();
            this.dialog.dialogFormVisible = false;
            this.$message.success(response.msg);
          }).catch((e) => {
            console.error(e);
            validateForm(e.data, this.addForm, this.addFormRules);
          });
        }
      }
    });
  }

  onSearch(): void {
    this.dataTable.refresh();
  }

  onRefreshSelectForm(): void {
    //恢复搜索默认信息
    this.selectForm.resetFields();
    this.onSearch();
  }

  handleRemove(file) {
    console.log(file);
  }

  handleDownload(file) {
    console.log(file);
  }
  /*选中事件*/
  handleSelectionChange(val:any): void {
    if (val) {
      this.dialog.isBatchRemoveDisabled = val.length <= 0;
      this.dialog.isBatchEditDisabled = val.length !== 1;
      
    }
    this.dialog.formData = val;
  }

  beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 20;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 6MB!');
        }
        return isJPG && isLt2M;
  }

  /*重置表单*/
  reset(): void {
    this.addModel = {
      purpose: '',
      name: '',
      deptId: '',
      status: '0',
      image:''
    };
    (this as any).resetForm('addForm');
  }

  /*关闭对话框*/
  closeDialog() {
    this.$nextTick(() => {
      this.reset();
    });
  }

  /*获取数据*/
  getData() {
    getSealList().then(response => {
      this.data = response.data;
      
    }).catch((e) => {
      console.error(e);
    });
    userTreeSelectDept().then(res =>{
         
        this.dialog.treeParams.data = res.data;
        if(this.treeSelect){
          this.treeSelect.treeDataUpdateFun(res.data);
        }
         if(this.searchTreeSelect){
          this.searchTreeSelect.treeDataUpdateFun(res.data);
         }
         
         
      }).catch((e) => {
        console.error(e);
      });
  }

  searchFun(value: any): void {
    this.treeSelect.filterFun(value);
  }

  searchTreeFun(value: any): void {
    this.searchTreeSelect.filterFun(value);
  }

  mounted() {
    this.getData();
  }
}
</script>

<style scoped lang="scss">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

